 # -*- coding: utf-8 -*-

import db
reload( db)
from db import McfConnector

import InstanceAttribute
reload( InstanceAttribute)
from InstanceAttribute import *



class Instance():
	"""Description of an instance"""
	def __init__( self, libmyCF, instance_id, ac_id, ae_id):
		self.libmyCF = libmyCF
		self.instance_id = instance_id
		self.ac_id = ac_id
		self.ae_id = ae_id


	def getAcquisition( self):
		return self.libmyCF.acquisitions.all_acquisitions[ self.ac_id ]


	def getAE( self):
		return self.libmyCF.ontology.all_AEs[ self.ae_id ]


	def getAttributes( self):
		attributes = []
		query="SELECT * FROM Instance_Attributes WHERE instances_id = \"%s\""%(self.instance_id)
		for data in self.libmyCF.connector.mcfQuery(query):
			attributes.append( Instance_Attribute( instand_attribute_id=int(data[0]), instance_id=int(data[1]), attribute_id=int(data[2]), value=data[3]))
		
		return attributes
		#TODO: recherche dans le modele theorique avec gestion d'heritage.


	def getAttributesNamed( self, name):
		"""Retrieve the attribute of this instance with the name 'name' from DataBase or create one from the theoretical informations if present"""
		attributes = []
		query="SELECT * FROM Instance_Attributes AS IA INNER JOIN (SELECT * FROM Attribute_Type WHERE name =\"%s\") AS AT ON ( IA.instance_attribute_type_id = AT.attribute_type_id) WHERE IA.instances_id = \"%d\""%( name, self.instance_id)
		for data in self.libmyCF.connector.mcfQuery(query):
			attributes.append( Instance_Attribute( libmyCF=self.libmyCF, instance_attribute_id=int(data[0]), instance_id=int(data[1]), attribute_type_id=int(data[2]), value=data[3]))
			break
		
		# If no result, search in the theoretical model.
		if len( attributes) == 0 :
			attribute = self.getAE().getAttributesNamed( name)
			if len(attribute) != 0:
				instanceAttribute = Instance_Attribute( libmyCF=self.libmyCF, instance_attribute_id=None, instance_id=self.instance_id, attribute_type_id=attribute[0].attribute_type_id, value=attribute[0].getValue())
				attributes.append( self.libmyCF.acquisitions.addInstanceAttribute( instanceAttribute))
		return attributes


	def getId( self):
		return self.instance_id


	def getName( self):
		return self.getAE().getName()
